package com.uinnova.product.eam.workable.listener;

import com.uinnova.product.eam.workable.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.engine.HistoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.flowable.variable.api.history.HistoricVariableInstance;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Slf4j
@Component("sendMessageToWorkbenchListener")
public class SendMessageToWorkbenchListener implements ExecutionListener {
    @Value("${eam.push.plan.notice}")
    private String eamPushPlanNoticeUrl;

    @Autowired
    private transient RuntimeService runtimeService;
    @Resource
    private transient RestTemplate restTemplate;
    @Autowired
    private transient HistoryService historyService;

    @Resource
    private HttpUtil httpUtil;

    @Override
    public void notify(DelegateExecution execution) {
        FlowElement currentFlowElement = execution.getCurrentFlowElement();
        String type = currentFlowElement.getDocumentation();
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                .processInstanceId(execution.getProcessInstanceId()).singleResult();
        //获取历史任务
        List<HistoricTaskInstance> historicTaskInstanceList = historyService.createHistoricTaskInstanceQuery()
                .processInstanceId(processInstance.getProcessInstanceId())
                .orderByHistoricTaskInstanceEndTime()
                .asc()
                .list();

        //上一任务
        HistoricTaskInstance h =null;
        for (HistoricTaskInstance historicTaskInstance : historicTaskInstanceList) {
            if(historicTaskInstance.getDeleteReason() ==null){
                h= historicTaskInstance;
                break;
            }
        }
        if(h==null){
            h = historicTaskInstanceList.get(0);
        }

        log.info("上一任务：{}", JSONObject.valueToString(h));
        List<HistoricVariableInstance> historicVariableInstanceList =  historyService.createHistoricVariableInstanceQuery()
                .processInstanceId(processInstance.getProcessInstanceId())
                .taskId(h.getId()).list();
        //获取上一个节点执行结果
        Map<String, Object> variables = historicVariableInstanceList.stream()
                .filter(v -> !StringUtils.isEmpty(v.getVariableName()))
                .filter(v -> v.getValue() != null)
                .collect(Collectors.toMap(HistoricVariableInstance::getVariableName, HistoricVariableInstance::getValue));
        log.info("变量：{}", JSONObject.valueToString(variables));
        //会签节点
        Object finalResult = variables.get("goOut");
        if (finalResult == null) {
            //单节点
            finalResult = variables.get("pass");
        }
        Map<String, String> params = new ConcurrentHashMap<>();
        params.put("result", finalResult.toString());
        if (type.equals("plan")) {
            params.put("sourceType", "plan");
        }else{
            params.put("sourceType", "diagram");
        }
        params.put("sourceId", processInstance.getBusinessKey());
        HistoricProcessInstance hi = historyService.createHistoricProcessInstanceQuery()
                .processInstanceId(execution.getProcessInstanceId())
                .singleResult();
        String startUserId = hi.getStartUserId();
        log.info("流程发起人[startUserId:{}]", startUserId);
        params.put("startUserId", startUserId);
        log.info("推送工作台方案审批消息:{}", JSONObject.valueToString(params));
        httpUtil.post(eamPushPlanNoticeUrl, params, Object.class);
    }
}
